package com.template.config.webmvc.interceptor;

import com.template.common.annotation.Authority;
import com.template.common.exception.PermissionException;
import com.template.service.SysMenuService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;

/**
 * 菜单权限是否启用拦截器
 */
@Component
@RequiredArgsConstructor
public class PermissionAliveInterceptor implements HandlerInterceptor {

    private final SysMenuService sysMenuService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod handlerMethod)) return true;

        // 获取接口所需要的权限
        Authority annotation = handlerMethod.getMethod().getAnnotation(Authority.class);
        if (annotation == null) return true;
        String[] requirePerms = annotation.value();

        List<String> aliveMenuPerms = sysMenuService.getAliveMenuPerms();
        for (String requirePerm : requirePerms) {
            if (aliveMenuPerms.contains(requirePerm)) {
                return true;
            }
        }
        throw new PermissionException("接口未启用");
    }
}
